package com.honeybee.cloud.framework.validation.text;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * @Description 密码检验注解实现
 * @Author cheng
 * @Create 2018-11-21
 * @Since 1.0.0
 */
@Slf4j
public class TextValidator implements ConstraintValidator<Text, String> {

    private String regex;
    private int max;
    private int min;
    private boolean enableNull;

    @Override
    public void initialize(Text text) {
        this.regex = text.regex();
        this.max = text.max();
        this.min = text.min();
        this.enableNull = text.enableNull();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
        log.debug("检验文本，检验值{}，可空:{},最大长度:{},最小长度:{},正则，{}", value, enableNull, max, min, regex);
        if (StringUtils.isEmpty(value) && enableNull) {
            log.debug("检验文本满足可空");
            return true;

        }
        if (StringUtils.isEmpty(value) && !enableNull) {
            log.debug("检验文本不满足可空");
            return false;
        }

        if (!StringUtils.isEmpty(regex) && !value.matches(regex)) {
            log.debug("检验文本，不满足正则");
            return false;
        }
        int length = value.length();
        if (length < min) {
            log.debug("检验文本，长度小于最小值");
            return false;
        }
        if (length > max) {
            log.debug("检验文本，长度大于最大值");
            return false;
        }
        log.debug("检验文本,通过所有检验");

        return true;
    }
}
